package com.jair.crawler.mi;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlInput;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;

import net.sf.json.JSONObject;

public class CommonWebClient {
	private boolean cookie_enable = false;
	public WebClient getClinet() throws FailingHttpStatusCodeException, IOException{
		WebClient webClient =  new WebClient(BrowserVersion.CHROME,"127.0.0.1",8888);//创建WebClient
		webClient.getOptions().setUseInsecureSSL(true);
		webClient.getOptions().setThrowExceptionOnScriptError(false);
		webClient.getOptions().setJavaScriptEnabled(false);
		webClient.getOptions().setCssEnabled(false);
		FileReader cookieFr = null;
		try {
			cookieFr = new FileReader("cookie");
			BufferedReader br = new BufferedReader(cookieFr);
			String line = "";
			while ( (line=br.readLine()) != null ) {
				 JSONObject jo = JSONObject.fromObject(line);
				 Cookie co = new Cookie(jo.getString("domain"), 
						 jo.getString("name"), 
						 jo.getString("value"), 
						 jo.getString("path"),null, 
						 (Boolean)jo.get("secure"), 
						 (Boolean)jo.get("httpOnly"));
				 webClient.getCookieManager().addCookie(co);
			}
			cookie_enable = true;
			cookieFr.close();
		}catch(FileNotFoundException e){
			System.out.println("没有cookie文件");
		}finally{
			if(cookieFr != null){
				cookieFr.close();
			}
		}
			return webClient;
	}
}
